<?php

namespace app\service;

use app\common\BaseService;
use app\model\StoreLoss as StoreLossModel;
use app\model\StoreLossOrder as StoreLossOrderModel;
use think\facade\Db;

class StoreLossService extends BaseService
{
  public static function getInstance(): StoreLossService
  {
    return parent::getInstance();
  }

  public static function getModel(): StoreLossOrderModel
  {
    return StoreLossOrderModel::getInstance();
  }
  public static function getDetailModel(): StoreLossModel
  {
    return StoreLossModel::getInstance();
  }

  public static function getDataByCondition($conditions, $order = ['id' => 'desc']) {
    return self::getModel()->getDataByCondition($conditions, $order);
  }

  public function getLossJoinStore($conditions, $order = ['s.id' => 'DESC']) {
    $conditions[] = ['sl.status', 1, '='];
    $query = Db::name('store_loss')
      ->alias('sl')
      ->field('sl.*, so.apply_number, so.apply_date, so.comment as order_comment, s.base, s.name, u.basename,s.category_id, c.category_name')
      ->join('store_house s', 's.id = sl.store_id', 'LEFT')
      ->join('store_loss_order so', 'so.id = sl.loss_id', 'LEFT')
      ->join('category c', 'c.id = s.category_id', 'LEFT')
      ->join('user u', 'u.base = s.base', 'LEFT');
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $query = $query->where($field, $op, $value);
    }
    $query = $query->order($order);
    return $query->select()->toArray();
  }

  /*
   * 批量损耗处理
   */
  public static function createMultiLoss($data, $sure)
  {
    $conditions[] = ['status', 1, '='];
    // 获取仓库数据
    $houseList = StoreService::getInstance()->getDataByCondition($conditions);
    $houseList = array_column($houseList, null, 'id');
    // 获取损耗申请号
    $cond = [
      ['insert_time', date('Y-m-d'), '>=']
    ];
    $outer = self::getModel()->getDataByCondition($cond);
    $arr = array_unique(array_column($outer, 'apply_number'));
    $num = str_pad(count($arr) + 1, 3, '0', STR_PAD_LEFT);
    $applyNumber = 'SH'.date('Ymd') . $num;
    // 新增损耗信息
    $insertLoss = [];
    $insertLossOrder = [
      'apply_number' => $applyNumber,
      'apply_date' => $data['apply_date'],
      'base' => $data['base'],
      'comment' => '',
      'status' => $sure ? 1 : 2,
      'insert_time' => date('Y-m-d H:i:s'),
      'last_update_time' => date('Y-m-d H:i:s')
    ];
    // 更新门店仓库
    $updateHouse = [];
    foreach ($data['detail'] as $value) {
      if (!isset($houseList[$value['store_id']])) {
        return ['status' => false, 'msg' => '该商品不存在'];
      }
      $house = $houseList[$value['store_id']];
      if ($house['count'] < $value['count']) {
        return ['status' => false, 'msg' => '该商品库存不足'];
      }
      $insertLoss[] = [
        'loss_id' => 0,
        'store_id' => $value['store_id'],
        'price_before' => $house['price'],
        'count_before' => $house['count'],
        'total_amount_before' => $house['total_amount'],
        'count' => strval($house['count']) - strval($value['count']),
        'comment' => $value['comment'],
        'status' => 1,
        'insert_time' => date('Y-m-d H:i:s'),
        'last_update_time' => date('Y-m-d H:i:s')
      ];
      if ($sure) {
        $updateHouse[] = [
          'id' => $value['store_id'],
          'count' => $value['count'],
          'total_amount' => round($value['count'] * $house['price'], 2),
          'last_update_time' => date('Y-m-d H:i:s')
        ];
      }
    }
    self::getModel()->startTrans();
    try {
      // 新增store_loss_order
      if ($insertLossOrder) {
        $res = self::getModel()
          ->insertGetId($insertLossOrder);
        if ($res === false) {
          throw new \Exception('新增store_loss_order失败');
        }
      }
      // 新增store_loss
      if ($insertLoss) {
        foreach ($insertLoss as &$v) {
          $v['loss_id'] = $res;
        }
        $res1 = self::getDetailModel()->insertAll($insertLoss);
        if (!$res1) {
          throw new \Exception('新增store_loss失败');
        }
      }
      // 修改store_house
      if ($updateHouse) {
        $res2 = StoreService::getModel()
          ->saveAll($updateHouse);
        if ($res2 === false) {
          throw new \Exception('修改store_house失败');
        }
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }

  }

  /*
   * 更新损耗处理
   */
  public static function updateMultiLoss($id, $data, $sure) {
    $conditions[] = ['status', 1, '='];
    // 获取仓库数据
    $houseList = StoreService::getInstance()->getDataByCondition($conditions);
    $houseList = array_column($houseList, null, 'id');
    // 新增损耗信息
    $insertLoss = [];
    $updateLossOrder = [];
    $updateHouse = [];
    if ($sure) {
      $updateLossOrder = [
        'status' => 1,
        'last_update_time' => date('Y-m-d H:i:s')
      ];
    }
    foreach ($data as $value) {
      if (!isset($houseList[$value['store_id']])) {
        return ['status' => false, 'msg' => '商品“'.$houseList[$value['store_id']]['name'].'”不存在'];
      }
      $house = $houseList[$value['store_id']];
      if ($house['count'] < $value['count']) {
        return ['status' => false, 'msg' => '商品“'.$houseList[$value['store_id']]['name'].'”库存不足'];
      }
      $insertLoss[] = [
        'loss_id' => $id,
        'store_id' => $value['store_id'],
        'price_before' => $house['price'],
        'count_before' => $house['count'],
        'total_amount_before' => $house['total_amount'],
        'count' => strval($house['count']) - strval($value['count']),
        'comment' => $value['comment'],
        'status' => 1,
        'insert_time' => date('Y-m-d H:i:s'),
        'last_update_time' => date('Y-m-d H:i:s')
      ];
      if ($sure) {
        $updateHouse[] = [
          'id' => $value['store_id'],
          'count' => $value['count'],
          'total_amount' => round($value['count'] * $house['price'], 2),
          'last_update_time' => date('Y-m-d H:i:s')
        ];
      }
    }

    self::getModel()->startTrans();
    try {
      // 新增store_loss_order
      if ($updateLossOrder) {
        $res = self::getModel()
          ->where('id', '=', $id)
          ->save($updateLossOrder);
        if ($res === false) {
          throw new \Exception('修改store_loss_order失败');
        }
      }
      // 删除store_loss
      $res1 = self::getDetailModel()
        ->where('loss_id', '=', $id)
        ->delete();
      if ($res1 === false) {
        throw new \Exception('删除store_loss失败');
      }
      // 新增store_loss
      if ($insertLoss) {
        $res2 = self::getDetailModel()->insertAll($insertLoss);
        if (!$res2) {
          throw new \Exception('新增store_loss失败');
        }
      }
      // 修改store_house
      if ($updateHouse) {
        $res2 = StoreService::getModel()
          ->saveAll($updateHouse);
        if ($res2 === false) {
          throw new \Exception('修改store_house失败');
        }
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }

  }

}